<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">绑定攻略列表</span>
          <div class="right-toolbar">
           
            <el-form :model="queryParams" ref="queryForm" inline class="search-form">
              <el-form-item label="攻略标题" prop="title">
                <el-input
                  v-model="queryParams.title"
                  placeholder="请输入攻略标题"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="primary" icon="Plus" @click="handleAdd">添加攻略</el-button>
                <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleBatchDelete">批量删除</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="id"
            label="ID"
            width="80"
            align="center"
          />
          <el-table-column
            prop="title"
            label="攻略标题"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="content"
            label="攻略内容"
            min-width="220"
            show-overflow-tooltip
          />
          <el-table-column
            label="商品图片"
            width="120"
            align="center"
          >
            <template #default="scope">
              <ImagePreview
                v-if="scope.row.productImage"
                :src="scope.row.productImage"
                :width="60"
                :height="60"
                fit="cover"
                class="product-image"
              />
              <div v-else class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="connectUrls"
            label="链接"
            min-width="180"
          >
            <template #default="scope">
              <div v-if="scope.row.connectUrls" class="link-list">
                <el-link 
                  v-for="(link, index) in scope.row.connectUrls.split(',')"
                  :key="index"
                  :href="link.trim()"
                  target="_blank"
                  type="primary"
                  class="link-item"
                >
                  链接{{ index + 1 }}
                </el-link>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="imgUrls"
            label="攻略图片"
            min-width="180"
          >
            <template #default="scope">
              <div v-if="scope.row.imgUrls" class="image-preview-list">
                <ImagePreview
                  :src="scope.row.imgUrls"
                  :width="60"
                  :height="60"
                  fit="cover"
                  class="table-image-preview"
                />
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="productId"
            label="商品ID"
            width="120"
            align="center"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            align="center"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleEdit(scope.row)"
                class="action-button"
              >编辑</el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row)"
                class="action-button"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          class="pagination"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑攻略对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="550px"
      destroy-on-close
      :close-on-click-modal="false"
      class="strategy-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="strategy-form"
      >
        <el-form-item label="攻略标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入攻略标题" clearable />
        </el-form-item>
        <el-form-item label="攻略内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="6"
            placeholder="请输入攻略内容" 
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="链接" prop="connectUrls">
          <el-input
            v-model="form.connectUrls"
            placeholder="请输入链接，多个链接用英文逗号分隔 (例如: http://example1.com,http://example2.com)"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="攻略图片" prop="imgUrls">
          <el-input
            v-model="form.imgUrls"
            placeholder="请输入图片链接，多个链接用英文逗号分隔 (例如: http://example1.com/img.jpg,http://example2.com/img.jpg)"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="绑定商品" prop="productId">
          <el-button type="primary" @click="openProductSelector">选择商品</el-button>
          <div v-if="selectedProduct.id" class="selected-product-info">
            <ImagePreview
              v-if="selectedProduct.image"
              :src="selectedProduct.image"
              :width="80"
              :height="80"
              fit="cover"
              class="selected-product-image"
            />
            <div class="selected-product-details">
              <div class="selected-product-name">{{ selectedProduct.name }}</div>
              <div class="selected-product-price">¥{{ selectedProduct.price }}</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog
      title="选择商品"
      v-model="productSelectorOpen"
      width="800px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="product-selector-header">
        <el-form :model="productQueryParams" inline>
          <el-form-item label="商品名称">
            <el-input 
              v-model="productQueryParams.name" 
              placeholder="请输入商品名称" 
              clearable 
              @keyup.enter="handleProductQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleProductQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetProductQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="productLoading"
        :data="productList"
        style="width: 100%"
        border
        stripe
        highlight-current-row
        @row-click="handleProductSelect"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        />
        <el-table-column
          prop="name"
          label="商品名称"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="price"
          label="价格"
          width="100"
          align="center"
        >
          <template #default="scope">
            <span class="price-tag">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="image"
          label="图片"
          width="120"
          align="center"
        >
          <template #default="scope">
            <ImagePreview
              v-if="scope.row.image"
              :src="scope.row.image"
              :width="60"
              :height="60"
              fit="cover"
              class="table-image-preview"
            />
            <div v-else class="image-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click.stop="handleProductSelect(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        v-model:current-page="productQueryParams.pageNum"
        v-model:page-size="productQueryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="productTotal"
        @size-change="handleProductSizeChange"
        @current-change="handleProductCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productSelectorOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import ImagePreview from '@/components/ImagePreview/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listProducts, getProduct } from '@/api/product/index'
import { uploadStrategy, updateStrategy, delStrategy, listStrategies } from '@/api/introduce/strategy'
import { Picture } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'

// 遮罩层
const loading = ref(false)
const submitLoading = ref(false)
const productLoading = ref(false)

// 选中数组
const ids = ref([])
const single = computed(() => ids.value.length !== 1)
const multiple = computed(() => !ids.value.length)

// 总条数
const total = ref(0)
const productTotal = ref(0)

// 表格数据
const tableData = ref([])
const productList = ref([])

// 弹出层标题
const title = ref("")
const open = ref(false)
const productSelectorOpen = ref(false)

// 表单参考
const formRef = ref(null)

// 表单参数
const form = reactive({
  id: undefined,
  title: '',
  content: '',
  productId: undefined,
  connectUrls: '',
  imgUrls: ''
})

// 选中的商品
const selectedProduct = reactive({
  id: undefined,
  name: '',
  price: '',
  image: ''
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: ''
})

// 商品查询参数
const productQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '攻略标题不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '攻略标题长度必须在2到100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '攻略内容不能为空', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请选择绑定商品', trigger: 'change' }
  ]
}

/** 查询攻略列表 */
const getList = () => {
  loading.value = true
  listStrategies(queryParams).then(response => {
    tableData.value = response.data.list || []
    total.value = response.data.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 查询商品列表 */
const getProductList = () => {
  productLoading.value = true
  listProducts(productQueryParams).then(response => {
    productList.value = response.data.list || []
    productTotal.value = response.data.total || 0
    productLoading.value = false
  }).catch(() => {
    productLoading.value = false
  })
}

/** 打开商品选择器 */
const openProductSelector = () => {
  productSelectorOpen.value = true
  getProductList()
}

/** 选择商品 */
const handleProductSelect = (row) => {
  console.log(row, 'handleProductSelect');
  
  selectedProduct.id = row.id
  selectedProduct.name = row.name
  selectedProduct.price = row.price
  selectedProduct.image = row.image
  
  // 更新表单数据
  if (!form.id) {
    // 新增时，设置productId
    form.productId = row.id
  } else {
    // 编辑时，设置productId
    form.productId = row.id
  }
  
  productSelectorOpen.value = false
  // 触发表单验证
  formRef.value?.validateField('productId')
}

/** 商品查询按钮操作 */
const handleProductQuery = () => {
  productQueryParams.pageNum = 1
  getProductList()
}

/** 重置商品查询 */
const resetProductQuery = () => {
  productQueryParams.name = ''
  productQueryParams.pageNum = 1
  getProductList()
}

/** 商品分页大小改变 */
const handleProductSizeChange = (val) => {
  productQueryParams.pageSize = val
  getProductList()
}

/** 商品分页页码改变 */
const handleProductCurrentChange = (val) => {
  productQueryParams.pageNum = val
  getProductList()
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  formRef.value?.resetFields()
  form.id = undefined
  form.title = ''
  form.content = ''
  form.productId = undefined
  
  // 重置选中的商品
  selectedProduct.id = undefined
  selectedProduct.name = ''
  selectedProduct.price = ''
  selectedProduct.image = ''
}

/** 添加按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = "添加攻略"
}

/** 修改按钮操作 */
const handleEdit = (row) => {
  reset()
  const id = row.id
  form.id = id
  form.title = row.title
  form.content = row.content
  form.productId = row.productId
  
  // 如果有商品ID，获取商品信息
  if (row.productId) {
    getProduct(row.productId).then(response => {
      const product = response.data
      selectedProduct.id = product.id
      selectedProduct.name = product.name
      selectedProduct.price = product.price
      selectedProduct.image = product.image
    })
  }
  
  open.value = true
  title.value = "编辑攻略"
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      
      // 验证商品选择
      if (!selectedProduct.id) {
        ElMessage.error('请选择绑定商品')
        submitLoading.value = false
        return
      }
      
      const formData = new FormData()
      
      if (title.value === "编辑攻略") {
        // 编辑攻略
        formData.append('id', form.id)
        formData.append('title', form.title)
        formData.append('content', form.content)
        formData.append('productId', form.productId)
        formData.append('connectUrls', form.connectUrls)
        formData.append('imgUrls', form.imgUrls)
        
        updateStrategy(formData).then(response => {
          ElMessage.success('编辑成功')
          open.value = false
          getList()
          submitLoading.value = false
        }).catch(() => {
          submitLoading.value = false
        })
      } else {
        // 添加新攻略
        formData.append('id', selectedProduct.id)
        formData.append('title', form.title)
        formData.append('content', form.content)
        formData.append('connectUrls', form.connectUrls)
        formData.append('imgUrls', form.imgUrls)
        
        uploadStrategy(selectedProduct.id, formData).then(response => {
          ElMessage.success('添加成功')
          open.value = false
          getList()
          submitLoading.value = false
        }).catch(() => {
          submitLoading.value = false
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('确认删除该攻略吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delStrategy(id).then(() => {
      ElMessage.success('删除成功')
      getList()
    })
  }).catch(() => {
    // 取消删除
  })
}

/** 批量删除按钮操作 */
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的${ids.value.length}条攻略吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 直接传递字符串数组，API会自动处理为逗号分隔的字符串
    delStrategy(ids.value).then(() => {
      ElMessage.success('批量删除成功')
      getList()
      // 清空选择
      ids.value = []
    })
  }).catch(() => {
    // 取消删除
  })
}

/** 选择条目触发事件 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => String(item.id))
}

/** 分页大小改变 */
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

/** 分页页码改变 */
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.title = ''
  queryParams.pageNum = 1
  getList()
}

// 初始化数据
getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.right-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-container {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.image-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
  font-size: 20px;
}

.price-tag {
  color: #ff6b6b;
  font-weight: bold;
}

.action-button {
  padding: 2px 0;
  margin-right: 8px;
}

.dialog-footer {
  text-align: right;
}

.strategy-form {
  max-height: 500px;
  overflow-y: auto;
}

.selected-product-info {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.selected-product-image {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.selected-product-image:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.link-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.link-item {
  font-size: 12px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selected-product-details {
  display: flex;
  flex-direction: column;
}

.selected-product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.selected-product-price {
  color: #ff6b6b;
}

.product-selector-header {
  margin-bottom: 15px;
}

.image-preview-list {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-image-preview {
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.table-image-preview:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>